package pers.cz.utils;

import pers.cz.model.SystemPartitionRelation;
import org.luaj.vm2.script.LuaScriptEngine;

import javax.script.*;
import java.util.Map;

/**
 * 分表规则配置，包括脚本执行引擎
 * @program: PostGirl-panent
 * @description: PartitionConfig
 * @author: Cheng Zhi
 * @create: 2022-04-21 09:21
 **/
public final class PartitionConfig {

    private String tableName;
    public Map<String, String> context;      // 脚本容器，the key is tableName, value is luaScript
    private ScriptEngine scriptEngine;       // 脚本执行引擎
    private LuaScriptEngine luaScriptEngine; // lua执行引擎
    private CompiledScript compiledScript;   // 脚本编译器
    private Integer schemaId;
    private Map<String, String> constParams; // 常量参数映射表
    private Map<String, SystemPartitionRelation> paramConfig;

    public PartitionConfig(String tableName) {
        this.tableName = tableName;
    }

    /**
     * 设置脚本编译器和执行引擎
     * @param luaScriptEngine
     * @param script
     * @throws ScriptException
     */
    public void setScriptEngine(LuaScriptEngine luaScriptEngine, String script) throws ScriptException {
        this.scriptEngine = luaScriptEngine;
        this.luaScriptEngine = luaScriptEngine;
        CompiledScript compile = luaScriptEngine.compile(script);
        this.compiledScript = compile;
    }

    /**
     *调用执行
     * @param bind
     * @return
     * @throws ScriptException
     */
    public boolean invokeRaw(Bindings bind) throws ScriptException {
        boolean success = true;
        try {
            compiledScript.eval(bind);
        } catch (Exception e) {
            success = false;
        }

        return success;
    }

    /**
     * 获取执行引擎范围
     * @return
     */
    Bindings getEngineBindings(){
        return luaScriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
    }






}
